#include "my_plugin.h"

#define MY_PLUGIN(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), my_plugin_get_type(), MyPlugin))

struct _MyPlugin
{
  GObject parent_instance;
};

G_DEFINE_TYPE(MyPlugin, my_plugin, g_object_get_type())

static void my_plugin_handle_method_call(MyPlugin *self, FlMethodCall *method_call)
{
  g_autoptr(FlMethodResponse) response = nullptr;

  const gchar *method = fl_method_call_get_name(method_call);

  if (strcmp(method, "getMsg") == 0)
  {
    g_autoptr(FlValue) result = fl_value_new_string("欢迎使用YFree_App：linux");
    response = FL_METHOD_RESPONSE(fl_method_success_response_new(result));
  }
  else if (strcmp(method, "goH5") == 0)
  {
    GtkWidget *dialog = gtk_message_dialog_new(NULL, GTK_DIALOG_DESTROY_WITH_PARENT, GTK_MESSAGE_INFO, GTK_BUTTONS_OK, NULL, NULL);
    gtk_window_set_title(GTK_WINDOW(dialog), "当前尚不支持");
    gtk_dialog_run(GTK_DIALOG(dialog));
    gtk_widget_destroy(dialog);
  }
  else if (strcmp(method, "goUniapp") == 0)
  {
    GtkWidget *dialog = gtk_message_dialog_new(NULL, GTK_DIALOG_DESTROY_WITH_PARENT, GTK_MESSAGE_INFO, GTK_BUTTONS_OK, NULL, NULL);
    gtk_window_set_title(GTK_WINDOW(dialog), "当前尚不支持");
    gtk_dialog_run(GTK_DIALOG(dialog));
    gtk_widget_destroy(dialog);
  }
  else
  {
    response = FL_METHOD_RESPONSE(fl_method_not_implemented_response_new());
  }

  fl_method_call_respond(method_call, response, nullptr);
}

static void my_plugin_dispose(GObject *object)
{
  G_OBJECT_CLASS(my_plugin_parent_class)->dispose(object);
}

static void my_plugin_class_init(MyPluginClass *klass)
{
  G_OBJECT_CLASS(klass)->dispose = my_plugin_dispose;
}

static void my_plugin_init(MyPlugin *self) {}

static void method_call_cb(FlMethodChannel *channel, FlMethodCall *method_call, gpointer user_data)
{
  MyPlugin *plugin = MY_PLUGIN(user_data);
  my_plugin_handle_method_call(plugin, method_call);
}

void MyPluginRegister(FlPluginRegistry *registry_in)
{
  MyPlugin *plugin = MY_PLUGIN(g_object_new(my_plugin_get_type(), nullptr));
  g_autoptr(FlStandardMethodCodec) codec = fl_standard_method_codec_new();
  g_autoptr(FlMethodChannel) channel = fl_method_channel_new(fl_plugin_registrar_get_messenger(fl_plugin_registry_get_registrar_for_plugin(registry_in, "")), "MyPlugin", FL_METHOD_CODEC(codec));
  fl_method_channel_set_method_call_handler(channel, method_call_cb, g_object_ref(plugin), g_object_unref);
  g_object_unref(plugin);
}

gchar *getArgument(FlMethodCall *method_call, gchar *name)
{
  FlValue *args = fl_method_call_get_args(method_call);
  if (fl_value_get_type(args) != FL_VALUE_TYPE_MAP)
  {
    return nullptr;
  }
  FlValue *value = fl_value_lookup_string(args, name);
  if (value == nullptr)
  {
    return nullptr;
  }
  return g_strdup(fl_value_get_string(value));
}